<?php
namespace Itdashu\SwoftThirdPartyService\Service\WeChat\Contracts;

// +----------------------------------------------------------------------
// | WeChatDeveloper
// +----------------------------------------------------------------------
// | 版权所有 2014~2018 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/WeChatDeveloper
// +----------------------------------------------------------------------

use Itdashu\SwoftThirdPartyService\Service\Base\PKCS7Encoder;
use Itdashu\SwoftThirdPartyService\Service\Base\Tools;

/**
 * 公众号消息 - 加解密
 * Class PrpCrypt
 */
class PrpCrypt
{

    public $key;

    /**
     * PrpCrypt constructor.
     * @param $key
     */
    public function __construct($key)
    {
        $this->key = base64_decode("{$key}=");
    }

  /**
   * 对明文进行加密
   * @param string $text 需要加密的明文
   * @param string $appId 公众号APPID
   * @return array
   */
    public function encrypt($text, $appId): ?array
    {
        try {
            $random = Tools::randomString(16);
            $iv = substr($this->key, 0, 16);
            $text = PKCS7Encoder::encode($random . pack('N', strlen($text)) . $text . $appId);
            $encrypted = openssl_encrypt($text, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv);
            return [ErrorCode::$OK, $encrypted];
        } catch (\Exception $e) {
            return [ErrorCode::$EncryptAESError, null];
        }
    }

    /**
     * 对密文进行解密
     * @param string $encrypted 需要解密的密文
     * @return array
     */
    public function decrypt($encrypted): ?array
    {
        try {
            $iv = substr($this->key, 0, 16);
            $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv);
        } catch (\Exception $e) {
            return [ErrorCode::$DecryptAESError, null];
        }
        try {
            $result = PKCS7Encoder::decode($decrypted);
            if (strlen($result) < 16) {
                return [ErrorCode::$DecryptAESError, null];
            }
            $content = substr($result, 16, strlen($result));
            $len_list = unpack('N', substr($content, 0, 4));
            $xml_len = $len_list[1];
            return [0, substr($content, 4, $xml_len), substr($content, $xml_len + 4)];
        } catch (\Exception $e) {
            return [ErrorCode::$IllegalBuffer, null];
        }
    }
}

